#! perl

sub msg {
   my ($self, $msg) = @_;

   my $overlay = $self->overlay (0, 0, $self->strwidth ($msg), 1);
   $overlay->set (0, 0, $msg);
   my $iow; $iow = urxvt::timer->new->after (2)->cb (sub {
      undef $overlay;
      undef $iow;
   });
}

sub on_init {
   my ($self) = @_;

   for (my $idx = 0; defined (my $res = $self->x_resource ("selection-autotransform-batz.$idx")); $idx++) {
      $res = $self->locale_decode ($res);
      my $transform = eval "sub { $res }";

      if ($transform) {
         push @{ $self->{transforms} }, $transform;
      } else {
         warn "$res: $@";
      }
   }

   $self->{enabled} = 1;

   push @{ $self->{term}{option_popup_hook} }, sub {
      ("autotransform" => $self->{enabled}, sub { $self->{enabled} = shift })
   };

   ()
}

sub on_sel_grab {
   my ($self) = @_;

   $self->{enabled}
      or return;

   my $text = $self->selection;
   local $_ = $text;

   for my $transform (@{ $self->{transforms} }) {
      $transform->();
      if ($text ne $_) {
         $self->selection ($_);
         # HACK to also add to the primary clipboard
         if (open(CLIPBOARD, "| xsel -ib")) {
            utf8::encode($_);
            print CLIPBOARD $_;
            close(CLIPBOARD);
         }
         s/[\x00-\x1f\x80-\x9f]/·/g;
         $self->msg ($self->special_encode ("auto-transformed to $_"));
         last;
      }
   }

   ()
}

